package com.roberto.simulation;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.utils.Array;
import com.roberto.entities.Invader;
import com.roberto.entities.Player;
import com.roberto.entities.Shield;
import com.roberto.entities.Shot;
import com.roberto.entities.UFO;
import com.roberto.main.Main;

public class GameLogic {
    public static final int MARGIN = 50;
    protected static boolean running;
    protected boolean invaderJustDied;
    public Array<Shot> bullets;
    public Sprite[] livesSprite;
    public Array<Invader> invaders;
    public Shield[] shields = new Shield[4];
    public UFO ufo;
    public Player player;
    public Shot playerShot = null;
    public long diedTick;
    public int score = 0;
    public int randomUfoScore;

    private Rectangle bulletBounds, playersBounds, invaderBounds;
    private float rate, speed, dead = 0;
    private float step = 10;
    private float minX, maxX, minY;
    private long invaderMoveTick, delayTick;
    private boolean gameOver, delayPermission, moveDown;
    private int weave = 1;

    public GameLogic() {
        populate();
    }

    private void populate() {
        bullets = new Array<Shot>();
        player = new Player();
        ufo = new UFO();

        // ======================== CREATES INVADER ROWS ========================//
        invaders = new Array<Invader>(5 * 11);
        int x = 0, y = 0;
        for (int i = 0; i < 5 * 11; i++) {
            x++;
            if (i % 11 == 0) {
                y++;
                x = 0;
            }
            invaders.add(new Invader(x, y));
        }
        // ====================================================================//
        for (int i = 0; i < shields.length; i++) {
            shields[i] = new Shield(i);
        }
        livesSprite = new Sprite[6];
        for (int i = 0; i < livesSprite.length; i++) {
            livesSprite[i] = player.getAliveSprite();
        }

        speed = 184 * 2 + (weave * 50);
        rate = 1000;
        running = true;
    }

    public void update(float delta) {
        restLogic();
        player.update(delta);
        if (running) {
            ufo.update(delta);
            updateInvaders(delta);
            updateShots(delta);
        }
        checkShipCollision();
        checkBlockCollision();
        checkInvaderCollision();
        checkGameState();
        removeDestroyedInvaders();

    }

    private void restLogic() {
        rate = rate <= 30 ? 30 : 1000 - speed - dead * 4;
        if (delayPermission && Main.getCurrentTime() - delayTick >= 170) {
            playerShot = null;
            delayPermission = false;
        }
        if (player.isDestroyed() && !gameOver && Main.getCurrentTime() - invaderMoveTick >= 1000) {
            running = true;
            player.revive();

        }

    }

    private void updateInvaders(float delta) {
        if (Main.getCurrentTime() - invaderMoveTick >= rate) {
            invaderMoveTick = Main.getCurrentTime();
            minX = Main.WIDTH;
            maxX = 0;
            minY = Main.HEIGHT;
            for (Invader invader : invaders) {
                if (moveDown) {
                    invader.move(step, true);
                } else {
                    invader.move(step, false);
                }
                invader.update(delta);
                minX = Math.min(minX, invader.x);
                minY = Math.min(minY, invader.y);
                if (maxX < invader.x + invader.width) {
                    maxX = invader.x + invader.width;
                }

            }
            if (!moveDown && (maxX >= Main.WIDTH - MARGIN - step / 2 || minX <= MARGIN)) {
                moveDown = true;
                step = -step;
                speed += 30;
            } else {
                moveDown = false;
            }
            Invader.playSound();
        }

    }

    private void updateShots(float delta) {
        for (int i = 0; i < bullets.size; i++) {
            bullets.get(i).update(delta);
            if (bullets.get(i).hasLeftField) {
                bullets.removeIndex(i);
            }

        }
        if ((playerShot != null && playerShot.hasLeftField) || bullets.size == 0) {
            playerShot = null;

        } else if (playerShot == null) {
            bullets.removeValue(playerShot, true);
        }

        if (MathUtils.random(Gdx.graphics.getFramesPerSecond() + 20) == 50) {
            int index = MathUtils.random(invaders.size - 2 <= 1 ? 1 : invaders.size - 2);
            if (index >= invaders.size) {
                index = 0;
            }

            bullets.add(new Shot(invaders.get(index).x, minY - 15, invaders.get(index).getID()));
        }
    }

    private void checkShipCollision() {
        for (Shot bullet : bullets) {
            playersBounds = player.getBounds();
            bulletBounds = bullet.getBounds();
            if (!bullet.isPlayers() && bulletBounds.overlaps(playersBounds)) {
                player.destroy();
                running = false;
                invaderJustDied = false;
                if (player.lives > 1) {
                    player.lives--;
                    invaderMoveTick = Main.getCurrentTime();
                } else {
                    player.lives--;
                    gameOver = true;
                }
                bullets.clear();
                break;
            }
        }

    }

    private void checkBlockCollision() {
        for (Shot bullet : bullets) {
            bulletBounds = bullet.getBounds();
            for (Shield shield : shields) {
                for (int j = 0; j < 10; j++) {
                    if (shield.getBounds(j).overlaps(bulletBounds)) {
                        shield.damageZone(j);
                        if (bullet.isPlayers()) {
                            bullets.removeValue(playerShot, false);
                            playerShot = null;
                            delayPermission = true;
                            delayTick = Main.getCurrentTime();
                        } else {
                            bullet.hasLeftField = true;
                        }

                        break;
                    }
                }
            }
        }

    }

    private void checkInvaderCollision() {
        if (playerShot == null || invaders.size == 0) {
            return;
        }

        for (Invader invader : invaders) {
            invaderBounds = invader.getBounds();
            bulletBounds = playerShot.getBounds();
            if (bulletBounds.overlaps(invaderBounds)) {
                invader.destroy();
                bullets.removeValue(playerShot, false);
                playerShot = null;
                invaderJustDied = true;
                diedTick = Main.getCurrentTime();
                dead++;
                score += invader.invPoints;
                break;

            }
        }
        if (ufo.onGameField() && ufo.getBounds().overlaps(bulletBounds)) {
            ufo.destroy();
            bullets.removeValue(playerShot, false);
            playerShot = null;
            invaderJustDied = true;
            diedTick = Main.getCurrentTime();
            randomUfoScore = MathUtils.random(5) * 50 + 100;
            score += randomUfoScore;
        }

    }

    private void removeDestroyedInvaders() {
        for (int i = 0; i < invaders.size; i++) {
            if (invaders.get(i).isDestroyed()) {
                invaders.removeIndex(i);
            }
        }
    }

    private void checkGameState() {
        if (invaders.size == 0 && player.lives > 0) {
            bullets.clear();
            playerShot = null;
            int lives = player.lives;
            populate();
            dead = 0;
            weave++;
            score += weave * 200 + lives * 200;
            player.lives = lives == 6 ? lives : lives + 1;
            Main.pref.setScore(score);
        } else if (player.lives == 0 || minY <= 120) {
            Main.pref.setScore(score);
            player.lives = 0;
            invaders.clear();
            bullets.clear();
            playerShot = null;
            running = false;
        }
    }

    public void moveShipLeft(float delta) {
        if (running) {
            player.x -= delta * Player.SHIP_VELOCITY;
            if (player.x <= MARGIN) {
                player.x = MARGIN;
            }
        }

    }

    public void moveShipRight(float delta) {
        if (running) {
            player.x += delta * Player.SHIP_VELOCITY;
            if (player.x >= Main.WIDTH - MARGIN - player.width) {
                player.x = Main.WIDTH - MARGIN - player.width;
            }
        }
    }

    public void shot() {
        if (playerShot == null && running && !delayPermission) {
            playerShot = new Shot(player.x + player.width / 2 - 2.3f, player.y + player.height);
            bullets.add(playerShot);
            player.shot();
        }
    }
}
